package com.ykdl.member.kid.sqlite;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.ykdl.member.base.QLog;
/**
 * 
 * DAO方式 访问数据库 文件的基类
 *
 * @since 1.0
 */
public class AbstractDB {

	public static final int DatabaseVersion = 1;
	/**
	 *  数据库内部版本号，2012-03-21 整合多个db为一个，修改为2
	 *  以后修改数据库的结构，和表结构后，需要修改这个值
	 */	
	public static final int INTERNAL_VERSION = 2;
	protected Context mContext;
	private  SQLiteDatabase db;
	private final static byte[] _writeLock = new byte[0]; //作为写锁
	public Context getmContext() {
		return mContext;
	}

	protected void getDBInstance() {
		checkDbOpen();
	}

	public AbstractDB(Context context) {
		this.mContext = context;
		getDBInstance();
	}

	public  void execute(String sql) throws SQLException {		
		synchronized (_writeLock) {
			checkDbOpen();
			db.execSQL(sql);
		}
	}

	public  void execute(String sql, Object[] arg) throws SQLException {
		synchronized (_writeLock) {
			checkDbOpen();
			try {
				db.execSQL(sql, arg);
			} catch (java.lang.IllegalStateException ee) {
				checkDbOpen();
				db.execSQL(sql, arg);
			}
		}
	}

	public  int delete(String table, String whereClause, String[] whereArgs) {		
		synchronized (_writeLock) {
			checkDbOpen();
			try {
				return db.delete(table, whereClause, whereArgs);
			} catch (Exception ee) {
				checkDbOpen();
				return db.delete(table, whereClause, whereArgs);
			}
		}
	}

	public  long insert(String table, String nullColumnHack, ContentValues values)
			throws SQLException {
		try {
			
			synchronized (_writeLock) {
				checkDbOpen();
				return db.insertOrThrow(table, nullColumnHack, values);
			}
		} catch (java.lang.Exception ee) {
			ee.printStackTrace();
			QLog.debug("db err========", "db err 3333333333333333333333");	
			close();
			try{
			synchronized (_writeLock) {
				checkDbOpen();
				return db.insertOrThrow(table, nullColumnHack, values);
			}
			}catch(Exception e){
				ee.printStackTrace();
				QLog.debug("db err========", "db err 4444444444444444");	
				close();
				synchronized (_writeLock) {
					checkDbOpen();
					return db.insertOrThrow(table, nullColumnHack, values);
				}
			}
		}
	}

	public  int update(String table, ContentValues values, String whereClause,
			String[] whereArgs) {
		
		synchronized (_writeLock) {
			checkDbOpen();
			return db.update(table, values, whereClause, whereArgs);
		}
	}

	public  Cursor query(String sql, String[] selectionArgs) {
		synchronized (_writeLock) {
		checkDbOpen();
		try {
			return db.rawQuery(sql, selectionArgs);
		} catch (Exception ee) {
			ee.printStackTrace();
			QLog.debug("AbstractDB===33333333333", ee.toString());
			return db.rawQuery(sql, selectionArgs);
		//	return query(sql, selectionArgs);
		}
		}
	}

	public  Cursor query(String table, String[] columns, String selection,
			String[] selectionArgs) {
		synchronized (_writeLock) {
		checkDbOpen();
		return db.query(table, columns, selection, selectionArgs, null, null,
				null);
		}
	}

//	public int getScalarValue(String sql, String[] selectionArgs) {
//		checkDbOpen();
//		int ret = 0;
//		Cursor c = query(sql, selectionArgs);
//
//		if (c.getCount() > 0) {
//			c.moveToFirst();
//			ret = c.getInt(0);
//		}
//
//		c.close();
//		return ret;
//	}

	/**
	 * This database to determine whether there
	 * 
	 * @param tableName
	 * @return
	 */
//	public int isExistTable(String tableName) {
//		checkDbOpen();
//		int count = 0;
//		String sql = "Select Count(*) From sqlite_master Where type='table' And name='"
//				+ tableName + "'";
//		count = this.getScalarValue(sql, null);
//		return count;
//	}

//	public void beginTransaction() {
//		checkDbOpen();
//		db.beginTransaction();
//	}
//
//	public void commit() {
//		db.setTransactionSuccessful();
//		db.endTransaction();
//	}
//
//	public void rollback() {
//		db.endTransaction();
//	}

	public  void close() {
		synchronized (_writeLock) {
		try {
			if (db != null && db.isOpen()) {
				db.close();
				db = null;
		//		QLog.debug("databbase been closed", "close ===================");
			}

		} catch (Exception e) {
			// TODO: handle exception
		}
		}
		
	
	}

	
	public   synchronized  int fetchNextRowid(){
		return 0;
	};
	
	public  boolean isOpen() {
		synchronized (_writeLock) {
		boolean result = false;
		if (db != null) {
			result = db.isOpen();
		}
		return result;
		}
	}

	private SQLiteOpenHelper dbHelper;

	protected  boolean checkDbOpen() {
		
		synchronized (_writeLock) {
		if (db == null) {
			if (dbHelper == null) {
				dbHelper = new DatabaseHelper(mContext);
			}
			db = dbHelper.getWritableDatabase();
			db.setLockingEnabled(true);
	//		QLog.debug("AbstractDB", "db is null ,open new data base ....");
			return true;
		} else if (!db.isOpen()) {
			if (dbHelper == null) {
				dbHelper = new DatabaseHelper(mContext);
			}
			db = dbHelper.getWritableDatabase();
			db.setLockingEnabled(true);
		//	QLog.debug("AbstractDB", " db colsed,open new data base ....");
			return true;
		}
		return false;
		}
	}
}
